package itdep.common.context.spring;


import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.domain.GrantedAuthoritySid;
import org.springframework.security.acls.domain.PrincipalSid;
import org.springframework.security.acls.model.AccessControlEntry;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.acls.model.Sid;

import java.util.Collections;

/**
 * @author Ivan Khalopik
 * @version $Revision: 4 $ $Date: 2010-06-10 13:13:16 +0000 (Thu, 10 Jun 2010) $
 */
public class Functions {
	public static final String PERMISSION_READ = "READ";
	public static final String PERMISSION_WRITE = "WRITE";
	public static final String PERMISSION_CREATE = "CREATE";
	public static final String PERMISSION_DELETE = "DELETE";
	public static final String PERMISSION_ADMINISTRATION = "ADMINISTRATION";

	public static boolean permission(AccessControlEntry ace, String permission) {
		return permission.equalsIgnoreCase(getPermission(ace.getPermission()));
	}

	public static boolean authority(AccessControlEntry ace, String authority) {
		return authority.equalsIgnoreCase(getAuthority(ace.getSid()));
	}

	protected static Object cast(final Object object, final Class<?>... types) {
		final Object target = object instanceof EntityObjectIdentity ?
				((EntityObjectIdentity) object).getEntity() : object;
		for (Class<?> type : types) {
			if (type.isInstance(target)) {
				return target;
			}
		}
		return Collections.emptyList();
	}

	protected static String getAuthority(Sid sid) {
		if (sid instanceof GrantedAuthoritySid) {
			return ((GrantedAuthoritySid) sid).getGrantedAuthority();
		}
		if (sid instanceof PrincipalSid) {
			return ((PrincipalSid) sid).getPrincipal();
		}
		return null;
	}

	protected static String getPermission(Permission permission) {
		if (permission.equals(BasePermission.READ)) {
			return PERMISSION_READ;
		} else if (permission.equals(BasePermission.WRITE)) {
			return PERMISSION_WRITE;
		} else if (permission.equals(BasePermission.DELETE)) {
			return PERMISSION_DELETE;
		} else if (permission.equals(BasePermission.CREATE)) {
			return PERMISSION_CREATE;
		} else if (permission.equals(BasePermission.ADMINISTRATION)) {
			return PERMISSION_ADMINISTRATION;
		}
		return null;
	}

}
